package com.tebiecloud.act.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tebiecloud.act.client.constants.ResultEnum;
import com.tebiecloud.act.client.model.entity.ActGoodsRef;
import com.tebiecloud.act.server.mapper.ActGoodsRefMapper;
import com.tebiecloud.act.server.service.ActGoodsRefService;
import com.tebiecloud.common.mybatis.base.service.impl.BaseServiceImpl;
import com.tebiecloud.common.utils.RedisUtils;
import com.tebiecloud.common.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * 活动关联的商品表 服务实现类
 * @author tebie
 * @date 2019-09-12
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ActGoodsRefServiceImpl extends BaseServiceImpl<ActGoodsRefMapper, ActGoodsRef> implements ActGoodsRefService {

    @Autowired
    ActGoodsRefMapper actGoodsRefMapper;

    @Autowired
    RedisUtils redisUtils;

    @Override
    public Map<String, String> updateStockQty(long actId, long goodsSpecificationId, int amount) {
        Map<String, String> resultMap = new HashMap<>();
        int time =  10;
        String key = UUIDUtil.get32UUID();
        boolean isLock = redisUtils.lock(key,time);
        if(!isLock){
            throw new RuntimeException("库存被占用，请稍等");
        }
        QueryWrapper<ActGoodsRef> actGoodsRefQueryWrapper = new QueryWrapper<>();
        actGoodsRefQueryWrapper.eq("act_id",actId);
        actGoodsRefQueryWrapper.eq("spec_id",goodsSpecificationId);
        actGoodsRefQueryWrapper.eq("deleted",0);
        ActGoodsRef actGoodsRef = actGoodsRefMapper.selectOne(actGoodsRefQueryWrapper);
        //计算库存
        if(!actGoodsRef.getStockQty().equals(-99)){
            int currentAmount = actGoodsRef.getStockQty() + amount;
            if(currentAmount<0){
                resultMap.put("status","error");
                resultMap.put("message", ResultEnum.ACT_STOCKQTY_ERROR.getMessage());
                return resultMap;
            }
            UpdateWrapper<ActGoodsRef> actGoodsRefUpdateWrapper = new UpdateWrapper<>();
            actGoodsRefUpdateWrapper.eq("act_id",actId);
            actGoodsRefUpdateWrapper.eq("spec_id",goodsSpecificationId);
            actGoodsRefUpdateWrapper.set("stock_qty",currentAmount);
            ActGoodsRef actGoodsRef1 = new ActGoodsRef();
            actGoodsRef1.setStockQty(currentAmount);
            actGoodsRefMapper.update(actGoodsRef1,actGoodsRefUpdateWrapper);
        }
        //解锁
        redisUtils.unLock(key);
        resultMap.put("status","OK");
        return resultMap;
    }
}
